using System.Text;
using System;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;
using Csla.Validation;
using BA.DAL;
using BA;

namespace BlazeApps.Library.Security
{
    [Serializable()]
    public class SecurityDetail : Csla.BusinessBase<SecurityDetail>
    {
        private BlazeApps.Library.ConfigSettings Config = new BlazeApps.Library.ConfigSettings();
        private BA.DAL.DBUtility DAL = new BA.DAL.DBUtility();
        private Procedures Procs = new Procedures();

        #region Business Properties and Methods

        //declare members
        private Guid _id = Guid.NewGuid();
        private Guid _secureitemid = Guid.Empty;
        private string _rolename = string.Empty;

        [System.ComponentModel.DataObjectField(true, false)]
        public Guid Id
        {
            get
            {
                CanReadProperty("Id", true);
                return _id;
            }
        }

        public Guid Secureitemid
        {
            get
            {
                CanReadProperty("Secureitemid", true);
                return _secureitemid;
            }
            set
            {
                CanWriteProperty("Secureitemid", true);
                if (!_secureitemid.Equals(value))
                {
                    _secureitemid = value;
                    PropertyHasChanged("Secureitemid");
                }
            }
        }

        public string Rolename
        {
            get
            {
                CanReadProperty("Rolename", true);
                return _rolename;
            }
            set
            {
                CanWriteProperty("Rolename", true);
                if (value == null)
                    value = string.Empty;
                if (!_rolename.Equals(value))
                {
                    _rolename = value;
                    PropertyHasChanged("Rolename");
                }
            }
        }

        protected override object GetIdValue()
        {
            return _id;
        }

        #endregion //Business Properties and Methods

        #region Validation Rules
        private void AddCustomRules()
        {
            //add custom/non-generated rules here...
        }

        private void AddCommonRules()
        {
            //
            // Rolename
            //
            ValidationRules.AddRule(CommonRules.StringRequired, "Rolename");
            ValidationRules.AddRule(CommonRules.StringMaxLength, new CommonRules.MaxLengthRuleArgs("Rolename", 256));
        }

        protected override void AddBusinessRules()
        {
            AddCommonRules();
            AddCustomRules();
        }
        #endregion //Validation Rules

        #region Authorization Rules
        protected override void AddAuthorizationRules()
        {
            //TODO: Define authorization rules in SecurityDetail
            //AuthorizationRules.AllowRead("Id", "SecurityDetailReadGroup");
            //AuthorizationRules.AllowRead("Secureitemid", "SecurityDetailReadGroup");
            //AuthorizationRules.AllowRead("Rolename", "SecurityDetailReadGroup");

            //AuthorizationRules.AllowWrite("Secureitemid", "SecurityDetailWriteGroup");
            //AuthorizationRules.AllowWrite("Rolename", "SecurityDetailWriteGroup");
        }


        public static bool CanGetObject()
        {
            //TODO: Define CanGetObject permission in SecurityDetail
            return true;
            //if (Csla.ApplicationContext.User.IsInRole("SecurityDetailViewGroup"))
            //	return true;
            //return false;
        }

        public static bool CanAddObject()
        {
            //TODO: Define CanAddObject permission in SecurityDetail
            return true;
            //if (Csla.ApplicationContext.User.IsInRole("SecurityDetailAddGroup"))
            //	return true;
            //return false;
        }

        public static bool CanEditObject()
        {
            //TODO: Define CanEditObject permission in SecurityDetail
            return true;
            //if (Csla.ApplicationContext.User.IsInRole("SecurityDetailEditGroup"))
            //	return true;
            //return false;
        }

        public static bool CanDeleteObject()
        {
            //TODO: Define CanDeleteObject permission in SecurityDetail
            return true;
            //if (Csla.ApplicationContext.User.IsInRole("SecurityDetailDeleteGroup"))
            //	return true;
            //return false;
        }
        #endregion //Authorization Rules

        #region Factory Methods
        private SecurityDetail()
        { /* require use of factory method */
        }

        public static SecurityDetail NewSecurityDetail()
        {
            if (!CanAddObject())
                throw new System.Security.SecurityException("User not authorized to add a SecurityDetail");
            return DataPortal.Create<SecurityDetail>();
        }

        public static SecurityDetail GetSecurityDetail(Guid id)
        {
            if (!CanGetObject())
                throw new System.Security.SecurityException("User not authorized to view a SecurityDetail");
            return DataPortal.Fetch<SecurityDetail>(new Criteria(id));
        }

        public static void DeleteSecurityDetail(Guid id)
        {
            if (!CanDeleteObject())
                throw new System.Security.SecurityException("User not authorized to remove a SecurityDetail");
            DataPortal.Delete(new Criteria(id));
        }

        public override SecurityDetail Save()
        {
            if (IsDeleted && !CanDeleteObject())
                throw new System.Security.SecurityException("User not authorized to remove a SecurityDetail");
            else if (IsNew && !CanAddObject())
                throw new System.Security.SecurityException("User not authorized to add a SecurityDetail");
            else if (!CanEditObject())
                throw new System.Security.SecurityException("User not authorized to update a SecurityDetail");

            return base.Save();
        }

        #endregion //Factory Methods

        #region Data Access

        #region Criteria

        [Serializable()]
        private class Criteria
        {
            public Guid Id;

            public Criteria(Guid id)
            {
                this.Id = id;
            }
        }

        #endregion //Criteria

        #region Data Access - Create
        [RunLocal]
        protected override void DataPortal_Create()
        {
            ValidationRules.CheckRules();
        }

        #endregion //Data Access - Create

        #region Data Access - Fetch
        private void DataPortal_Fetch(Criteria criteria)
        {
            ExecuteFetch(criteria);
        }

        private void ExecuteFetch(Criteria criteria)
        {
            DAL.CreateDBObjects(Config.ConnectionString, Config.Provider);

            DAL.AddParameter("@id", criteria.Id);

            using(SafeDataReader dr = new SafeDataReader(DAL.ExecuteReader(Procs.GetSecurityByID.ToString().Trim(), CommandType.Text, ConnectionState.Open)))
            {
                FetchObject(dr);
                ValidationRules.CheckRules();

                //load child object(s)
                FetchChildren(dr);
            }
        }

        private void FetchObject(SafeDataReader dr)
        {
            dr.Read();
            _id = dr.GetGuid("id");
            _secureitemid = dr.GetGuid("secureitemid");
            _rolename = dr.GetString("rolename");
        }

        private void FetchChildren(SafeDataReader dr)
        {
        }
        #endregion //Data Access - Fetch

        #region Data Access - Insert
        protected override void DataPortal_Insert()
        {
            ExecuteInsert();
        }

        private void ExecuteInsert()
        {
            DAL.CreateDBObjects(Config.ConnectionString, Config.Provider);

            AddInsertParameters(ref DAL);

            DAL.ExecuteNonQuery(Procs.InsertSecurity.ToString().Trim(), CommandType.Text, ConnectionState.Open);
        }

        private void AddInsertParameters(ref BA.DAL.DBUtility DAL)
        {
            DAL.AddParameter("@id", _id);
            DAL.AddParameter("@secureitemid", _secureitemid);
            DAL.AddParameter("@rolename", _rolename);
        }
        #endregion //Data Access - Insert

        #region Data Access - Update
        protected override void DataPortal_Update()
        {
            if (base.IsDirty)
            {
                ExecuteUpdate();
            }
        }

        private void ExecuteUpdate()
        {
            DAL.CreateDBObjects(Config.ConnectionString, Config.Provider);

            AddUpdateParameters(ref DAL);

            DAL.ExecuteNonQuery(Procs.UpdateSecurity.ToString().Trim(), CommandType.Text, ConnectionState.Open);
        }

        private void AddUpdateParameters(ref BA.DAL.DBUtility DAL)
        {
            DAL.AddParameter("@id", _id);
            DAL.AddParameter("@secureitemid", _secureitemid);
            DAL.AddParameter("@rolename", _rolename);
        }

        private void UpdateChildren(SqlConnection cn)
        {
        }
        #endregion //Data Access - Update

        #region Data Access - Delete
        protected override void DataPortal_DeleteSelf()
        {
            DataPortal_Delete(new Criteria(_id));
        }

        private void DataPortal_Delete(Criteria criteria)
        {
            ExecuteDelete(criteria);
        }

        private void ExecuteDelete(Criteria criteria)
        {
            DAL.CreateDBObjects(Config.ConnectionString, Config.Provider);

            AddDeleteParameters(ref DAL, criteria);

            DAL.ExecuteNonQuery(Procs.DeleteSecurity.ToString().Trim(), CommandType.Text, ConnectionState.Open);
        }

        private void AddDeleteParameters(ref BA.DAL.DBUtility DAL, Criteria criteria)
        {
            DAL.AddParameter("@id", criteria.Id);
        }
        #endregion //Data Access - Delete
        #endregion //Data Access
    }
}
